package com.it.controller;

import com.github.pagehelper.PageInfo;
import com.it.domain.Bills;
import com.it.domain.Goods;
import com.it.domain.Goods_Details;
import com.it.service.BillsService;
import com.it.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private BillsService billsService;

    /**
     * 新增货物
     *
     * @param goods
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/save.do")
    public ModelAndView GoodsSave(Goods goods, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView mv = new ModelAndView();

        //将前台数据放入goods
        goods.setName(request.getParameter("name"));
        goods.setProduct_Types(request.getParameter("Product_Types"));
        /*goods.setQuantity(Integer.parseInt(request.getParameter("Quantity")));
        //String转换成date类型
        DateFormat df = new SimpleDateFormat("mm/dd/yyyy");
        Date date = df.parse(request.getParameter("Production_Date"));
        goods.setProduction_Date(date);
        goods.setShelf_life(Integer.parseInt(request.getParameter("Shelf_life")));
        goods.setPurchase_price(Double.parseDouble(request.getParameter("Purchase_price")));
        goods.setShipping_price(Double.parseDouble(request.getParameter("Shipping_price")));*/
        goods.setSupplier(request.getParameter("Supplier"));
        goods.setSupplier_Contact(request.getParameter("Supplier_Contact"));

        //插入数据库request.getParameter("Supplier_Contact")
        goodsService.saveGoods(goods);

        //跳转页面
        String st = "新增数据成功！";
        mv.addObject("return_as", st);
        mv.setViewName("returnBack");

        return mv;

    }

    /**
     * 货物详情新增
     *
     * @param goods
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/goodsDetailsSave.do")
    public ModelAndView GoodsDetailsSave(Bills bills,Goods_Details goods, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //查询goods的id，放入goodsdetails的id
        List<Goods> goodsList = goodsService.FindByName(request.getParameter("name"), 1, 4);
        Goods goods1 = goodsList.get(0);
        Integer id = goods1.getId();

        goods.setId_d(id);
        goods.setName(request.getParameter("name"));
        goods.setDetails(request.getParameter("details"));
        goods.setQuantity(Integer.parseInt(request.getParameter("Quantity")));
        //String转换成date类型
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
        Date date = df.parse(request.getParameter("Production_Date"));
        goods.setProduction_Date(date);
        goods.setShelf_life(Integer.parseInt(request.getParameter("Shelf_life")));
        goods.setPurchase_price(Double.parseDouble(request.getParameter("Purchase_price")));
        goods.setShipping_price(Double.parseDouble(request.getParameter("Shipping_price")));


        System.out.println(goods);
        ModelAndView mv = new ModelAndView();


        //添加进入bills订单
        bills.setPay_out(Double.parseDouble(request.getParameter("Purchase_price"))*Integer.parseInt(request.getParameter("Quantity")));
        bills.setProfit(0-Double.parseDouble(request.getParameter("Purchase_price"))*Integer.parseInt(request.getParameter("Quantity")));
        bills.setCredit(0);
        bills.setReason("新订单，入库商品:"+request.getParameter("name")+"("+request.getParameter("details")+")"+"，数量为："+Integer.parseInt(request.getParameter("Quantity")));
        Date date1 = new Date();
        bills.setOperation_date(date1);
        billsService.insertBills(bills);

        try {

            goodsService.saveGoods_Details(goods);
            //跳转页面
            String st = "新增数据成功！";
            mv.addObject("return_as", st);
            mv.setViewName("returnBack");


        } catch (Exception e) {
            String st = "新增数据失败！";
            mv.addObject("return_as", st);
            mv.setViewName("returnBack");
        }

        return mv;


    }

    /**
     * @param page
     * @param size
     * @param model
     * @param goods
     * @param request
     * @param response
     * @return
     */

    @RequestMapping("/findAllGoods.do")
    public ModelAndView findAllGoods(@RequestParam(name = "page", required = true, defaultValue = "1") int page,
                                     @RequestParam(name = "size", required = true, defaultValue = "5") int size,
                                     Model model, Goods goods, HttpServletRequest request,
                                     HttpServletResponse response) {
        ModelAndView mv = new ModelAndView();

        List<Goods> allGoods = goodsService.findAllGoods(page, size);

        System.out.println(allGoods);
        Goods goods1 = allGoods.get(0);
        System.out.println(goods1);
        //page分页
        PageInfo pageInfo = new PageInfo(allGoods);
        mv.addObject("lists", pageInfo);
        mv.setViewName("goods_Find");

        return mv;

    }

    /**
     * 根据名称模糊查询货物
     *
     * @param page
     * @param size
     * @param model
     * @param goods
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/findByName.do")
    public ModelAndView FindByName(@RequestParam(name = "page", required = true, defaultValue = "1") int page,
                                   @RequestParam(name = "size", required = true, defaultValue = "5") int size,
                                   Model model, Goods goods, HttpServletRequest request,
                                   HttpServletResponse response) {
        ModelAndView mv = new ModelAndView();
        //根据名称查询
        List<Goods> goodsList = goodsService.FindByName(request.getParameter("name"), page, size);

        PageInfo pageInfo = new PageInfo(goodsList);
        mv.addObject("lista", pageInfo);
        mv.setViewName("goods_findlist");
        return mv;

    }

    /**
     * 修改goods表
     * 同时修改goodsdetails表名称
     * 根据id
     *
     * @param page
     * @param size
     * @param model
     * @param goods
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/changeById.do")
    public ModelAndView ChangeById(@RequestParam(name = "page", required = true, defaultValue = "1") int page,
                                   @RequestParam(name = "size", required = true, defaultValue = "5") int size,
                                   Model model, Goods goods, HttpServletRequest request,
                                   HttpServletResponse response) {
        ModelAndView mv = new ModelAndView();

        try {
            System.out.println("启动");
            String rname = request.getParameter("name");
            int id_d = Integer.parseInt(request.getParameter("id"));

            //查询出原有名字
            List<Goods> goodsList = goodsService.FindById(id_d);
            String name = goodsList.get(0).getName();
            //goodsdetails里面是否存在
            //不存在直接修改goods
            //存在连goodsdetails的name一起修改
            List<Goods_Details> goods_details = goodsService.FindByNameGD(name);
            System.out.println(3);
            String name1 = goods_details.get(0).getName();
            System.out.println("name1:" + name1);
            if (null == name1 || "".equals(name1) || name1.length() == 0) {
                //为空的情况
                /*goods.setId(Integer.parseInt(request.getParameter("id")));*/
                goods.setName(rname);

                goods.setProduct_Types(request.getParameter("Product_Types"));
                goods.setSupplier(request.getParameter("Supplier"));
                goods.setSupplier_Contact(request.getParameter("Supplier_Contact"));
                goodsService.changeGoods(goods);
            } else {
                //不为空的情况
                //改变goodsdetails表name
                //根据id修改名称
                goods_details.get(0).setName(rname);

                Goods_Details goods_details1 = new Goods_Details();
                goods_details1.setName(rname);
                goods_details1.setId_d(id_d);
                goodsService.ChangeGDName(goods_details1/*,id_d*/);

                //改变goods表
                /*goods.setId(Integer.parseInt(request.getParameter("id")));*/

                goods.setName(rname);

                goods.setProduct_Types(request.getParameter("Product_Types"));
                goods.setSupplier(request.getParameter("Supplier"));
                goods.setSupplier_Contact(request.getParameter("Supplier_Contact"));
                goodsService.changeGoods(goods);

                //跳转页面
                String st = "修改数据成功！";
                mv.addObject("return_as", st);
                mv.setViewName("returnBack");

            }
        } catch (Exception e) {
            //跳转页面
            String st = "修改数据失败！";
            mv.addObject("return_as", st);
            mv.setViewName("returnBack");
        }


        return mv;

    }

    /**
     * 根据id删除goods表和goods details表内容
     *
     * @param model
     * @param goods
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/deleById.do")
    public ModelAndView DeleById(Model model, Goods goods, HttpServletRequest request,
                                 HttpServletResponse response) {
        ModelAndView mv = new ModelAndView();

        int i = Integer.parseInt(request.getParameter("id"));
        try {
            goodsService.delGoods(i);
            goodsService.delGoodsDetails(i);
            String st = "修改删除成功！";
            mv.addObject("return_as", st);
            mv.setViewName("returnBack");
        } catch (Exception e) {
            String st = "修改删除失败！";
            mv.addObject("return_as", st);
            mv.setViewName("returnBack");

        }
        return mv;

    }

    /**
     * 根据名称查询货物详情
     *
     * @param page
     * @param size
     * @param goods_details
     * @param goods
     * @param request
     * @param response
     * @return
     * @throws ParseException
     */
    @RequestMapping("/selectGoodsDetails.do")
    public ModelAndView SelectGoodsDetails(@RequestParam(name = "page", required = true, defaultValue = "1") int page,
                                           @RequestParam(name = "size", required = true, defaultValue = "5") int size,
                                           Goods_Details goods_details, Goods goods, HttpServletRequest request,
                                           HttpServletResponse response) throws ParseException {
        ModelAndView mv = new ModelAndView();
        String name = request.getParameter("name");
        List<Goods_Details> goods_details1 = goodsService.SelectGoodsDetails(name, page, size);
        PageInfo pageInfo = new PageInfo(goods_details1);
        mv.addObject("listb", pageInfo);


        mv.setViewName("goodsdetails_findlist");
        return mv;

    }

    /**
     * 根据details删除货物
     *
     * @param request
     * @return
     */
    @RequestMapping("/delGoodsDetailsBydetails.do")
    public ModelAndView DelGoodsDetailsBydetails(Bills bills, ModelAndView mv, HttpServletRequest request) {

        try {
            //记录账单
            List<Goods_Details> goods_details = goodsService.FindGoodsByDetails(request.getParameter("details"));
            Goods_Details goods_details1 = goods_details.get(0);
            String name = goods_details1.getName();
            String details = goods_details1.getDetails();
            int a = goods_details1.getQuantity();
            double payout = goods_details1.getQuantity() * goods_details1.getPurchase_price();

            bills.setPay_out(payout);
            bills.setProfit(0-payout);
            bills.setCredit(0);
            bills.setReason("销毁"+name+"("+details+")"+"，数量为："+a);
            Date date = new Date();
            bills.setOperation_date(date);

            billsService.insertBills(bills);



            //删除货物操作
            goodsService.delGoodsDetailsBydetails(request.getParameter("details"));
            String st = "删除成功！";
            mv.addObject("return_as", st);
            mv.setViewName("returnBack");
        } catch (Exception e) {
            String st = "删除失败！";
            mv.addObject("return_as", st);
            mv.setViewName("returnBack");

        }
        return mv;
    }

    /**
     * 根据details改变相应goods details信息
     *
     * @param mv
     * @param request
     * @return
     * @throws ParseException
     */
    @RequestMapping("/changeDetails.do")
    public ModelAndView ChangeDetails(ModelAndView mv, HttpServletRequest request) throws ParseException {
        Goods_Details goods_details = new Goods_Details();
        goods_details.setDetails(request.getParameter("details"));
        goods_details.setQuantity(Integer.parseInt(request.getParameter("Quantity")));
        System.out.println(request.getParameter("Production_Date"));
        //String转换成date类型
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy/HH/mm/ss");
        Date date = df.parse(request.getParameter("Production_Date")+"/08/00/00");

        goods_details.setProduction_Date(date);
        goods_details.setShelf_life(Integer.parseInt(request.getParameter("Shelf_life")));
        goods_details.setPurchase_price(Double.parseDouble(request.getParameter("Purchase_price")));
        goods_details.setShipping_price(Double.parseDouble(request.getParameter("Shipping_price")));


        goodsService.ChangeDetails(goods_details);

        String st = "修改成功！";
        mv.addObject("return_as", st);
        mv.setViewName("returnBack");
        return mv;
    }

    /**
     * 出货数量
     *
     * @param mv
     * @param request
     * @return
     */
    @RequestMapping("/selectQuantity.do")
    public ModelAndView selectQuantity(Bills bills,ModelAndView mv, HttpServletRequest request) {

        int num = Integer.parseInt(request.getParameter("num"));

        String details = request.getParameter("details");

        //添加bills订单
        List<Goods_Details> goods_details1 = goodsService.FindGoodsByDetails(details);
        Goods_Details goods_details2 = goods_details1.get(0);
        String name = goods_details2.getName();
        double v = goods_details2.getShipping_price() * num;
        bills.setCredit(v);
        bills.setProfit(v);
        bills.setPay_out(0);
        bills.setReason("出库"+name+"("+details+")"+"，数量为："+num);
        Date date = new Date();
        bills.setOperation_date(date);
        //存入表单
        billsService.insertBills(bills);


        try {

            int i = goodsService.selectQuantity(details) - num;

            Goods_Details goods_details = new Goods_Details();
            goods_details.setQuantity(i);
            goods_details.setDetails(details);
            goodsService.IoDGoodsDetails(goods_details);

            String st = "修改成功！";
            mv.addObject("return_as", st);
            mv.setViewName("returnBack");
        } catch (Exception e) {
            String st = "修改失败！";
            mv.addObject("return_as", st);
            mv.setViewName("returnBack");
        }

        return mv;

    }

    /**
     * 根据details模糊查询
     * @param page
     * @param size
     * @param mv
     * @param goods_details
     * @param goods
     * @param request
     * @param response
     * @return
     * @throws ParseException
     */
    @RequestMapping("/findBydetails.do")
    public ModelAndView FindBydetails(@RequestParam(name = "page", required = true, defaultValue = "1") int page,
                                      @RequestParam(name = "size", required = true, defaultValue = "5") int size,
                                      ModelAndView mv,
                                      Goods_Details goods_details, Goods goods, HttpServletRequest request,
                                      HttpServletResponse response) throws ParseException {
        try {
            List<Goods_Details> details = goodsService.FindBydetails(request.getParameter("details"), page, size);
            PageInfo pageInfo = new PageInfo(details);
            mv.addObject("listb",pageInfo);
            mv.setViewName("goodsdetails_findlist1");
        } catch (Exception e) {
            String st = "修改失败！";
            mv.addObject("return_as", st);
            mv.setViewName("returnBack");
        }
        return mv;
    }

    /**
     * 根据details查询所有goods信息
     * @param page
     * @param size
     * @param mv
     * @param goods_details
     * @param goods
     * @param request
     * @param response
     * @return
     * @throws ParseException
     */
    @RequestMapping("/findAlldetails.do")
    public ModelAndView FindAlldetails(@RequestParam(name = "page", required = true, defaultValue = "1") int page,
                                      @RequestParam(name = "size", required = true, defaultValue = "5") int size,
                                      ModelAndView mv,
                                      Goods_Details goods_details, Goods goods, HttpServletRequest request,
                                      HttpServletResponse response) throws ParseException {
        try {
            List<Goods_Details> goods_details1 = goodsService.FindAlldetails(page, size);
            PageInfo pageInfo = new PageInfo(goods_details1);
            mv.addObject("listb",pageInfo);
            mv.setViewName("goodsdetails_findlist2");
        } catch (Exception e) {
            String st = "修改失败！";
            mv.addObject("return_as", st);
            mv.setViewName("returnBack");
        }
        return mv;
    }

    /**
     * 根据物品类型查询
     * @param page
     * @param size
     * @param mv
     * @param goods_details
     * @param goods
     * @param request
     * @param response
     * @return
     * @throws ParseException
     */
    @RequestMapping("/findSomeGoods.do")
    public ModelAndView FindSomeGoods(@RequestParam(name = "page", required = true, defaultValue = "1") int page,
                                       @RequestParam(name = "size", required = true, defaultValue = "5") int size,
                                       ModelAndView mv,
                                       Goods_Details goods_details, Goods goods, HttpServletRequest request,
                                       HttpServletResponse response) throws ParseException {
        String product_types = request.getParameter("Product_Types");

        List<Goods> goodsList = goodsService.FindSomeGoods(product_types, page, size);
        PageInfo pageInfo = new PageInfo(goodsList);
        mv.addObject("list01",pageInfo);
        mv.setViewName("goods_findlistSel");
        return mv;

    }

    /**
     * 查询所有过期食品
     * @param page
     * @param size
     * @param mv
     * @param goods_details
     * @param goods
     * @param request
     * @param response
     * @return
     * @throws ParseException
     */
    @RequestMapping("/findExpiredGoods.do")
    public ModelAndView FindExpiredGoods(@RequestParam(name = "page", required = true, defaultValue = "1") int page,
                                      @RequestParam(name = "size", required = true, defaultValue = "5") int size,
                                      ModelAndView mv,
                                      Goods_Details goods_details, Goods goods, HttpServletRequest request,
                                      HttpServletResponse response) throws ParseException {
        List<Goods_Details> goods_details1 = goodsService.FindAlldetails(page, size);
        List<Goods_Details> goods_out = new ArrayList<>();
        for (Goods_Details gd:goods_details1
        ){

            //判断日期 是否过期
            long time = (long)gd.getProduction_Date().getTime()+(long)gd.getShelf_life()*24*60*60*1000;

            Date date = new Date();

            if ((date.getTime()>time)){


                goods_out.add(gd);
            }

        }

        PageInfo pageInfo = new PageInfo(goods_out);
        mv.addObject("list_gd",pageInfo);
        mv.setViewName("goodsdetails_Expried");
        return mv;
    }

    /**
     * 即将过期货物
     * @param page
     * @param size
     * @param mv
     * @param goods_details
     * @param goods
     * @param request
     * @param response
     * @return
     * @throws ParseException
     */
    @RequestMapping("/FindExpiredDateGoods.do")
    public ModelAndView FindExpiredDateGoods(@RequestParam(name = "page", required = true, defaultValue = "1") int page,
                                         @RequestParam(name = "size", required = true, defaultValue = "5") int size,
                                         ModelAndView mv,
                                         Goods_Details goods_details, Goods goods, HttpServletRequest request,
                                         HttpServletResponse response) throws ParseException {
        int num = Integer.parseInt(request.getParameter("num"));

        List<Goods_Details> goods_details1 = goodsService.FindAlldetails(page, size);
        List<Goods_Details> goods_out = new ArrayList<>();
        for (Goods_Details gd:goods_details1
        ){

            //判断日期 是否过期
            long time = (long)gd.getProduction_Date().getTime()+(long)gd.getShelf_life()*24*60*60*1000+num*24*60*60*1000;

            Date date = new Date();

            if ((date.getTime()>time)){


                goods_out.add(gd);
            }

        }
        PageInfo pageInfo = new PageInfo(goods_out);
        mv.addObject("list_gd",pageInfo);
        mv.setViewName("goodsdetails_DateExpried");
        return mv;

    }


}
